const md5 = require('blueimp-md5')
const DB = require('../tools/mysql')

module.exports = async ctx => {
  const { username, password, timestamp } = ctx.request.body

  const [user] = await DB('user').select('*').where('loginname', username).andWhere('status', 1)

  if (user && user.password === md5(`tpgj${password}`)) {

    let role = [],
      place = [],
      auth = []

    const roles = user.role.split(',')
    for (let r = 0; r < roles.length; r++) {
      const [list] = await DB('role').select('*').where('id', roles[r])
      list && role.push(list)
    }

    // let authstr = role.reduce((auth, next) => (auth.authorization || '') + ',' + (next.authorization || ''))
    let authstr = ''
    role.forEach((item, index) => {
      authstr += ((index === 0 ? '' : ',') + item.authorization)
    })
    const authset = new Set(authstr.split(','))
    for (let a of authset) {
      const [list] = await DB('func').select('*').where({ id: a, enable: 1 })
      list && auth.push(list)
    }

    const places = user.place.split(',')
    for (let p = 0; p < places.length; p++) {
      const [list] = await DB('placename').select('placename.id', 'placename.pid', 'placename.name as pname', 'organization.level', 'organization.name as oname').leftJoin('organization', 'placename.org', 'organization.id').where('placename.id', places[p])
      list && place.push(list)
    }

    ctx.body = { code: 1, msg: '登录成功', data: { ...user, role, place, auth } }

  } else {
    ctx.body = { code: 0, msg: '用户名或密码错误' }
  }

}